#include <compilation/task/Task.h>


namespace compilation
{


void VirtualAgenda::addNewAsFirst(VirtualTask* task)
{
  m_tasks.push_front(task);
  DEBUG_INSTRUCTION_VISITOR
      << "  inserted in front"
      << std::endl;
}


void VirtualAgenda::addNewAsLast(VirtualTask* task)
{
  m_tasks.push_back(task);
  DEBUG_INSTRUCTION_VISITOR
      << "  inserted at the end"
      << std::endl;
}


void
VirtualAgenda::addNewSorted(VirtualTask* virtualTask)
{
  DEBUG_INSTRUCTION_VISITOR
      << "add new sorted"
      << std::endl;

  if (!m_tasks.empty())
  {
    std::list<VirtualTask*>::iterator iter = m_tasks.begin();
    std::auto_ptr<VirtualTask> task(virtualTask);

    Comparison compare = (*iter)->compare(*virtualTask);
    while (compare < CEqual)
    {
      if (++iter != m_tasks.end())
        compare = (*iter)->compare(*virtualTask);
      else
        break;
    }

    /**/ if (compare == CEqual)
    {
      if (!(*iter)->mergeWith(*task))
      {
        m_tasks.insert(iter, task.release());
        if ((*iter)->hasInstruction())
        {
          DEBUG_INSTRUCTION_VISITOR
              << "  inserted after task on "
              << (*iter)->getInstruction().getRegistrationIndex()
              << std::endl;
        }
        else
        {
          DEBUG_INSTRUCTION_VISITOR
              << "  inserted after unidentified task"
              << std::endl;
        }
      }
      else
      {
        if ((*iter)->hasInstruction())
        {
          DEBUG_INSTRUCTION_VISITOR
              << "  merged with task on "
              << (*iter)->getInstruction().getRegistrationIndex()
              << std::endl;
        }
        else
        {
          DEBUG_INSTRUCTION_VISITOR
              << "  merged with unidentified task"
              << std::endl;
        }
      }
    }
    else if (compare == CGreater)
    {
      m_tasks.insert(iter, task.release());
      if ((*iter)->hasInstruction())
      {
        DEBUG_INSTRUCTION_VISITOR
            << "  insert after task on "
            << (*iter)->getInstruction().getRegistrationIndex()
            << std::endl;
      }
      else
      {
        DEBUG_INSTRUCTION_VISITOR
            << "  insert after unidentified task"
            << std::endl;
      }
    }
    else if (compare == CLess)
    {
      DEBUG_INSTRUCTION_VISITOR
          << "  inserted at the end"
          << std::endl;
      m_tasks.push_back(task.release());
    }
  }
  else
  {
    DEBUG_INSTRUCTION_VISITOR
        << "  inserted at the end"
        << std::endl;
    m_tasks.push_back(virtualTask);
  }
}


} // compilation
